package top.crossrun.webview.bridge.webview.SysWebView;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.GeolocationPermissions;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;

import top.crossrun.webview.bridge.core.R;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;

/**
 * create by Run
 * on 2020/8/24 11:21
 * do
 */
public class SysWebViewChromeClientBak extends WebChromeClient {
    private int REQUEST_CODE_FILE_CHOOSER = 1;
    private Activity activity;
    private FrameLayout fullScreenView;

    private ValueCallback<Uri> mUploadCallbackForLowApi;
    private ValueCallback<Uri[]> mUploadCallbackForHighApi;

    /**
     * @param REQUEST_CODE_FILE_CHOOSER 发起文件选择时候的code
     * @param activity
     * @param fullScreenView            如果有需要全屏播放的话，传入一个全屏的Framelayout，否则全屏播放无效
     */
    public SysWebViewChromeClientBak(int REQUEST_CODE_FILE_CHOOSER, Activity activity, FrameLayout fullScreenView) {
        this.REQUEST_CODE_FILE_CHOOSER = REQUEST_CODE_FILE_CHOOSER;
        this.activity = activity;
        this.fullScreenView = fullScreenView;
    }

    @Override
    public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
        callback.invoke(origin, true, false);
        super.onGeolocationPermissionsShowPrompt(origin, callback);
    }

    View myVideoView;
    View myNormalView;
    CustomViewCallback callback;

    @Override
    public void onShowCustomView(View view, CustomViewCallback customViewCallback) {
        if (fullScreenView == null) {
            return;
        }
        ViewGroup viewGroup = (ViewGroup) fullScreenView.getParent();
        viewGroup.removeView(fullScreenView);
        viewGroup.addView(view);
        myVideoView = view;
        myNormalView = fullScreenView;
        callback = customViewCallback;
    }

    @Override
    public void onHideCustomView() {
        if (fullScreenView == null) {
            return;
        }
        if (callback != null) {
            callback.onCustomViewHidden();
            callback = null;
        }
        if (myVideoView != null) {
            ViewGroup viewGroup = (ViewGroup) myVideoView.getParent();
            viewGroup.removeView(myVideoView);
            viewGroup.addView(myNormalView);
        }
    }

    public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
        mUploadCallbackForHighApi = filePathCallback;
        Intent intent = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            intent = fileChooserParams.createIntent();
        } else {
            intent = getFilerChooserIntent();
        }
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            activity.startActivityForResult(intent, REQUEST_CODE_FILE_CHOOSER);
        } catch (ActivityNotFoundException e) {
            mUploadCallbackForHighApi = null;
            Toast.makeText(activity, R.string.web_open_file_chooser_failed, Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

    @Override
    public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) {
        AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
        builder.setTitle("信息提示");
        builder.setMessage(message);//这个message就是alert传递过来的值
        //添加一个EditText
        final EditText editText = new EditText(view.getContext());
        editText.setText(defaultValue);//这个就是prompt 输入框的默认值
        //添加到对话框
        builder.setView(editText);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //获取edittext的新输入的值
                String newValue = editText.getText().toString().trim();
                result.confirm(newValue);//处理确定按钮了，且过jsresult传递，告诉js点击的是确定按钮(参数就是输入框新输入的值，我们需要回传到js中)
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                result.cancel();//处理取消按钮，且过jsresult传递，告诉js点击的是取消按钮
            }
        });
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);//默认true，设置false后，按对话框以外的地方不起作用（按返回键还起作用）
        //防止对话框消失后未处理js事件，而一直占用焦点
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                result.cancel();//告诉js点击的是取消按钮
            }
        });
        dialog.show();
        return true;
    }

    // 拦截JS的警告框
    @Override
    public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
        AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
        builder.setTitle("信息提示");
        builder.setMessage(message);//这个message就是alert传递过来的值
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //处理确定按钮，且通过jsresult传递，告诉js点击的是确定按钮
                result.confirm();
            }
        });
        AlertDialog dialog = builder.create();
        //防止对话框消失后未处理js事件，而一直占用焦点
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                result.cancel();//告诉js点击的是取消按钮
            }
        });
        dialog.show();
        return true;
    }

    // 拦截JS的确认框
    @Override
    public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
        AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
        builder.setTitle("信息提示");
        builder.setMessage(message);//这个message就是alert传递过来的值
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                result.confirm();//告诉js点击的是确定按钮
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                result.cancel();//告诉js点击的是取消按钮
            }
        });
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);//默认true，设置false后，按对话框以外的地方不起作用（按返回键还起作用）
        //防止对话框消失后未处理js事件，而一直占用焦点
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                result.cancel();//告诉js点击的是取消按钮
            }
        });
        dialog.show();
        return true;
    }

    // For Android > 4.1.1
    @SuppressWarnings("unused")
    public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                String AcceptType, String capture) {
        this.openFileChooser(uploadMsg);
    }

    // For Android 3.0+
    @SuppressWarnings("unused")
    public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                String AcceptType) {
        this.openFileChooser(uploadMsg);
    }

    // For Android < 3.0
    public void openFileChooser(ValueCallback<Uri> uploadMsg) {
        mUploadCallbackForLowApi = uploadMsg;
        activity.startActivityForResult(Intent.createChooser(getFilerChooserIntent(), "File Chooser"), REQUEST_CODE_FILE_CHOOSER);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_FILE_CHOOSER && (resultCode == RESULT_OK || resultCode == RESULT_CANCELED)) {
            afterFileChooseGoing(resultCode, data);
        }
    }

    private void afterFileChooseGoing(int resultCode, Intent data) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (mUploadCallbackForHighApi == null) {
                return;
            }
            mUploadCallbackForHighApi.onReceiveValue(FileChooserParams.parseResult(resultCode, data));
            mUploadCallbackForHighApi = null;
        } else {
            if (mUploadCallbackForLowApi == null) {
                return;
            }
            Uri result = data == null ? null : data.getData();
            mUploadCallbackForLowApi.onReceiveValue(result);
            mUploadCallbackForLowApi = null;
        }
    }

    private Intent getFilerChooserIntent() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        return intent;
    }
}
